package logic

import (
	"context"
	"strconv"

	"demo/internal/svc"
	"demo/internal/types"
	"demo/model"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type QuestionDeleteLogic struct {
	logx.Logger
	ctx    context.Context
	rds *redis.Redis
	svcCtx *svc.ServiceContext
	modelQ model.QuestionModel
	modelO model.OptionModel
}

func NewQuestionDeleteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QuestionDeleteLogic {
	rds, err := redis.NewRedis(redis.RedisConf{
		Host: svcCtx.Config.Redis.Host,
		Pass: svcCtx.Config.Redis.Pass,
		Type: svcCtx.Config.Redis.Type,
	})
	if err != nil {
		logx.Errorf("redis init error: %v", err)
	}
	return &QuestionDeleteLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		rds: rds,
		modelQ: model.NewQuestionModel(svcCtx.Orm),
		modelO: model.NewOptionModel(svcCtx.Orm),
	}
}

func (l *QuestionDeleteLogic) QuestionDelete(req *types.QuestionDeleteRequest) (resp *types.CommonResponse, err error) {
	// todo: add your logic here and delete this line
	l.rds.DelCtx(l.ctx,QuestionDetailPrefix + strconv.FormatInt(req.Id,10))
	// 首先需要将qst_sort顺序排对
	question,err := l.modelQ.FindOne(l.ctx,nil,req.Id)
	if err != nil {
		return nil,err
	}
	lastQuestion,err := l.modelQ.FindOneByQstSort(l.ctx,nil,req.Id)
	if err != sqlx.ErrNotFound && lastQuestion != nil {
		lastQuestion.QstSort = question.QstSort
	}
	l.modelQ.Update(l.ctx,nil,lastQuestion)
	// 删除问题同时删除附属的问题选项
	err = l.modelO.DeleteByQuestionId(l.ctx,nil,req.Id)
	if err != nil {
		return nil,err
	}
	err = l.modelQ.Delete(l.ctx,req.Id)
	if err != nil {
		return nil,err
	}
	return &types.CommonResponse{
		Code: 200,
		Msg: "删除成功",
	},nil
}
